import { Avatar, Button, Flex, Input, Upload } from "antd"
import { useEffect, useState } from "react"
import { reqDelFile } from "../api/uploadApi"

type Props<T>={
    label:string,
    content:string,
    status:boolean
    type?:"text"|"img"
    EditFn?:()=>void
    CloseFn?:()=>void
    updateFn?:(obj:T) =>void
}

export const Edit =<T,>({ 
    status,
    content,
    type,
    EditFn,
    CloseFn,
    updateFn,
    label,
}:Props<T>)=>{
    const [value,setValue] =useState("")
    useEffect(()=>{
        if(status){
            setValue("")
        }
    },[status])
    const statusEdit =(
        <Flex gap={20} align="center">
            {type == "img" ? (
                <Upload 
                listType="picture-circle"
                action="/dev-api/api/upload"
                name="file"
                onChange={async (e)=>{
                    if(e.file.status === "done"){
                        setValue(e.file.response.data)
                    }
                    if(e.file.status === "removed"){
                        await reqDelFile(value)
                        setValue("")
                    }
                }}>{value === "" && "+"}</Upload>
            ):(
                <Input 
                defaultValue={content}
                onChange={(e)=>setValue(e.target.value)}></Input>
            )}
            <Button type="primary" onClick={()=>updateFn && updateFn({[label]:value} as T)}>确认修改</Button>
            <Button onClick={CloseFn}>取消</Button>
        </Flex>
    )

    const  statusShow=(
        <Flex gap={20} align="center">
            {type == "img" ? (
                <Avatar size={64} src={content}></Avatar>
            ):(
                <div>{content}</div>
            )}
            <Button type="primary" size="small" onClick={EditFn}>修改</Button>
        </Flex>
    )
    return status ? statusEdit :statusShow
}












